﻿using System.Collections.Concurrent;

namespace SqlSugar
{
    public static partial class ISqlSugarClientExtension
    {
        private readonly static ConcurrentDictionary<string, EntityColumnInfo> _entityKeyColumnInfo = new ConcurrentDictionary<string, EntityColumnInfo>();

        public static EntityColumnInfo GetEntityPrimaryKeyProperty<TEntity>(this ISqlSugarClient @this)
          where TEntity : class, new()
        {
            var key = typeof(TEntity).FullName;
            return _entityKeyColumnInfo.GetOrAdd(key, key =>
            {
                var entityInfo = @this.EntityMaintenance.GetEntityInfo<TEntity>();
                var primaryKeys = entityInfo.Columns.Where(a => a.IsPrimarykey);
                if (primaryKeys.Count() < 1)
                {
                    throw new ArgumentNullException($"{entityInfo.Type.FullName}缺少IsPrimaryKey=true的属性");
                }
                if (primaryKeys.Count() > 1)
                {
                    throw new ArgumentNullException($"{entityInfo.Type.FullName}包含多个IsPrimaryKey=true的属性");
                }
                return primaryKeys.First();
            });
        }
    }
}
